﻿using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using SeCompUFSCarWeb.Models;

namespace SeCompUFSCarWeb.Account
{
    public partial class Register : Page
    {
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            string course;
            string school = "UFSCar";
            
            if (SchoolRadio.SelectedValue != "UFSCar")
                school = School.Text;

            switch (CourseRadio.SelectedValue)
            {
                case "Engenharia de Computação":
                    course = "Engenharia de Computação";
                    break;
                case "Ciência da Computação":
                    course = "Ciência da Computação";
                    break;
                default:
                    course = Course.Text;
                    break;
            }

            var manager = new UserManager();
            var user = new ApplicationUser() {
                UserName = UserName.Text,
                Email = UserName.Text,
                FullName = FullName.Text,
                School = school,
                Course = course,
                Year = Convert.ToInt32(Year.Text)
            };

            IdentityResult result = manager.Create(user, Password.Text);
            if (result.Succeeded)
            {
                //To modify UserRole on the scope of this application use uncomment the line above and Change "Staff" to "Admin", leave commented to keep the deafault role.
                //manager.AddToRole<ApplicationUser>(user.Id, "Staff");
                IdentityHelper.SignIn(manager, user, isPersistent: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else 
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
    }
}